package com.example.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

public class DdSignUtils {

    /**
     * ⽣生成签名参数
     * @param params
     * @return
     */
    public static String buildParamsString(Map<String, String> params) {
        List<String> result = new ArrayList<>(params.size());
        for (Map.Entry<String, String> param : params.entrySet()) {
            if ("key".equals(param.getKey())) {
                continue;
            }
            result.add(param.getKey() + "=" + param.getValue());
        }

        Collections.sort(result);

        return StringUtils.join(result, "&");
    }
    
    /**
     * ⽣生成签名
     * @param params
     * @return
     */
    public static String getSign(String params, String secret) {
        return DigestUtils.md5Hex(params + "&key=" + secret);
    }
    
    /**
     * 签名检测
     * @param params
     * @param key
     * @return
     */
    public static boolean check(String params, String key, String secret) {
        String sign = getSign(params, secret);
        return sign.equals(key);
    }
}